import type { AnalysisResult } from '../types/dialogue';

export type AnalysisStep = {
  id: string;
  name: string;
  description: string;
};

export const analysisSteps: AnalysisStep[] = [
  { id: 'reportId', name: '初始化分析', description: '开始分析' },
  { id: 'contextSummary', name: '上下文分析', description: '分析上下文' },
  { id: 'interactionAnalysis', name: '互动分析', description: '分析互动' },
  { id: 'strategicInsights', name: '策略洞察', description: '获取策略洞察' },
  { id: 'conflictAssessment', name: '冲突评估', description: '评估冲突' },
  { id: 'optimizationRecommendations', name: '优化建议', description: '获取优化建议' }
];

interface ContinuationMessage {
  content: string;
}

interface AnalysisMessage {
  content: string[];
  continue: boolean;
  user?: string;
}

export class DialogueAnalysisWebSocket {
  private ws: WebSocket | null = null;
  private readonly url: string;
  private static instances: DialogueAnalysisWebSocket[] = [];
  private pageUnloadHandler: (() => void) | null = null;

  constructor(url: string = 'wss://xyz.wwh-ai-sites.xin/dialogue_analyze/') {
    this.url = url;
    DialogueAnalysisWebSocket.instances.push(this);
    
    // 添加页面卸载事件监听
    this.pageUnloadHandler = this.handlePageUnload.bind(this);
    window.addEventListener('beforeunload', this.pageUnloadHandler);
  }

  private handlePageUnload(): void {
    this.disconnect();
  }

  connect(callbacks: {
    onProgress?: (step: AnalysisStep) => void;
    onResult?: (result: AnalysisResult) => void;
    onError?: (error: string) => void;
    onOpen?: () => void;
    onClose?: () => void;
    onMessage?: (data: string) => void;
  }): void {
    if (this.ws?.readyState === WebSocket.OPEN) {
      console.warn('WebSocket connection already exists');
      return;
    }

    this.ws = new WebSocket(this.url);

    this.ws.onopen = () => {
      console.log('WebSocket connected');
      callbacks.onOpen?.();
    };

    this.ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (typeof data === 'string') {
          const step = analysisSteps.find(s => s.id === data);
          if (step) {
            callbacks.onProgress?.(step);
            return;
          }
          callbacks.onMessage?.(data);
        } else if (this.isContinuationMessage(data)) {
          callbacks.onMessage?.(data.content);
        } else if (this.isAnalysisResult(data)) {
          callbacks.onResult?.(data);
        } else {
          console.warn('Received unknown message format:', data);
        }
      } catch (e) {
        // If JSON parsing fails, check if it's a step ID
        const step = analysisSteps.find(s => s.id === event.data);
        if (step) {
          callbacks.onProgress?.(step);
        } else {
          // If not a step ID, treat as plain text message
          callbacks.onMessage?.(event.data);
        }
      }
    };

    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error);
      callbacks.onError?.('连接错误，请稍后重试');
    };

    this.ws.onclose = () => {
      console.log('WebSocket disconnected');
      callbacks.onClose?.();
      this.ws = null;
    };
  }

  private isContinuationMessage(data: any): data is ContinuationMessage {
    return typeof data === 'object' && 
           data !== null && 
           typeof data.content === 'string';
  }

  private isAnalysisResult(data: any): data is AnalysisResult {
    return typeof data === 'object' && 
           data !== null && 
           (data.reportId !== undefined || 
            data.contextSummary !== undefined || 
            data.interactionAnalysis !== undefined || 
            data.strategicInsights !== undefined || 
            data.conflictAssessment !== undefined || 
            data.optimizationRecommendations !== undefined);
  }

  sendAnalysis(content: string | string[], user?: string): void {
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      throw new Error('WebSocket connection not established');
    }

    const message: AnalysisMessage = {
      content: Array.isArray(content) ? content : [content],
      continue: false,
      user
    };

    this.ws.send(JSON.stringify(message));
  }

  sendContinuation(content: string, user?: string): void {
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      throw new Error('WebSocket connection not established');
    }

    const message: AnalysisMessage = {
      content: [content],
      continue: true,
      user
    };

    this.ws.send(JSON.stringify(message));
  }

  disconnect(): void {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
    
    // 移除页面卸载事件监听
    if (this.pageUnloadHandler) {
      window.removeEventListener('beforeunload', this.pageUnloadHandler);
      this.pageUnloadHandler = null;
    }
    
    const index = DialogueAnalysisWebSocket.instances.indexOf(this);
    if (index !== -1) {
      DialogueAnalysisWebSocket.instances.splice(index, 1);
    }
  }

  isConnected(): boolean {
    return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
  }

  static disconnectAll(): void {
    [...DialogueAnalysisWebSocket.instances].forEach(instance => {
      instance.disconnect();
    });
  }
}

export default DialogueAnalysisWebSocket;
